import Data from '@/api/data'
import Message from '@/utils/message'
import Notification from '@/utils/notification'
import permission from '@/directive/permission'
import checkPermission from '@/utils/permission'
import { Loading } from 'element-ui'
let loding
export default {
  directives: { permission },
  data() {
    return {
      listQuery: {
        key: '',
        page: 1,
        size: 10,
        status: null
      },
      dialogType: '', // 对话框类型 add添加 edit修改
      dialogMap: {
        add: '添加',
        edit: '修改'
      },
      list: [], // 数据列表
      listLoading: true, // 加载显示效果 true加载显示 false加载隐藏
      total: 0, // 数据总数
      dialogVisible: false, // 对话框显示效果  true显示  false隐藏
      checkOutList: [], // 多选列表
      imgQuality: 0.5, // 压缩图片的质量
      uploadLoading: false,
      statusOptions: [ // 可选  查询状态下拉选择
        {
          value: null,
          label: '全部状态'
        },
        {
          value: 1,
          label: '正常'
        },
        {
          value: 0,
          label: '禁用'
        }
      ],
      searchBtnLoading: false, // 搜索
      dataBtnLoading: false, // 确认
      delBtnLoading: false, // 删除
      batchDelBtnLoading: false // 批量删除
      // priority: false
    }
  },
  created() {
    // 模板渲染前
    if (this.priority) {
      return
    } else {
      this.fetchList()
    }
  },
  methods: {
    selectChange(){
      this.changePage()
      this.fetchList()
    },
    inputClear(){
      this.fetchList()
    },
    //logo删除时的钩子函数
    logoRemove(file, fileList){
      this.formData.path = ''
    },
    //文件上传失败的钩子函数
    handError(){
      this.$message.error('上传失败！');
    },
    //限制上传个数
    handExceed(){
       this.$message.warning('上传个数有限，请先删除一个再上传！');
    },
    //文件上传时读条
    handPreview(file) {
      console.log(file);
    },
    //广告文件上传成功的钩子函数
    uploadCoverMore(response, file, fileList){
      this.formData.path = response.src
      this.$message.success('上传成功！');
    },
    checkPermission,
    selectable(row, index) {
      if (row.code === 'admin' || row.code === 'applet' || row.username === 'admin') {
        return false
      }
      return true
    },
    // selectable(row, index) {
    //   if (row.code === 'admin' || row.username === 'admin') {
    //     if (this.checkPermission(['admin'])) {
    //       return true
    //     }
    //     return false
    //   }
    //   return true
    // },
    handleFilter() { // 点击搜索按钮
      if (this.listQuery.key.length > 64) {
        Message({
          message: '查询输入请控制在64个字符以内',
          type: 'error'
        })
        return
      }
      this.listQuery.page = 1
      this.fetchList()
    },
    async fetchList() {
      this.listLoading = true
      this.searchBtnLoading = true
      const obj = JSON.parse(JSON.stringify(this.listQuery))
      for (const key in obj) {
        if (obj[key] === null || obj[key] === '') {
          delete obj[key]
        }
      }
      const res = await Data.get(this.apiUrl, obj)
      if (res) {
        this.list = res.list
        this.total = res.total
        this.listLoading = false
        this.searchBtnLoading = false
      }
    },
    handleSelectionChange(value) { // 多选改变
      this.checkOutList = value
    },
    changePage() { // 改变分页显示条数始终跳回第一页
      this.listQuery.page = 1
    },
    showDialog(type, row = null) { // 显示对话框
      if (type === 'edit') {
        for (const key in this.formData) {
          if (row[key]) {
            this.formData[key] = row[key]
          }
        }
        if(this.formData.path){
          let path = {
            name:'IMG',
            url: this.formData.path
          }
          this.fileList.push(path)
        }
        this.formData.id = row.id
        if (row.startTime && row.endTime && row.startTime.length > 0 && row.endTime.length > 0) {
          this.$set(this.formData, 'time', [
            row.startTime,
            row.endTime
          ])
        }
      }
      this.dialogType = type
      this.dialogVisible = true
    },
    closeDialog() {
      this.fileList=[]
      this.resetForm()
      this.$nextTick(() => {
        if (this.$refs['form']) {
          this.$refs['form'].clearValidate()
        }
      })
    },
    handleDelete(type, id = null) { // 删除/批量删除
      if (type === 'batch') {
        if (!this.checkOutList.length > 0) {
          Message({
            type: 'error',
            message: '请勾选需要删除的数据'
          })
          return
        }
      }
      this.$confirm('是否确定删除?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          const array_id = []
          if (type === 'batch') { // 批量
            for (const i of this.checkOutList) {
              // 选中列表id  追加到数组
              array_id.push(i.id)
            }
            this.batchDelBtnLoading = true
          }
          if (type === 'once') { // 单次
            array_id.push(id)
            this.delBtnLoading = true
          }
          const res = await Data.delete(this.apiUrl+'/'+ array_id)
          if (res) {
            Notification({
              message: '删除成功!'
            })
            this.fetchList()
            if (type === 'batch') { this.batchDelBtnLoading = false } else { this.delBtnLoading = false }
          }
        })
        .catch(() => {})
    },
    handleToggleStatus(row) { // 状态按钮启用停用
      const tip = row.status ? '是否确认禁用' : '是否确认启用'
      this.$confirm(tip, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          // 确认
          const data = {
            id: row.id,
            status: row.status ? 0 : 1
          }
          const res = await Data.edit(this.apiUrl, data)
          if (res) {
            this.fetchList()
            Notification({
              message: row.status ? '禁用成功' : '启用成功'
            })
          }
        })
        .catch(() => {}) // 取消
    },
    formSubmit(type, objData = null, message = null) {
      let res, tip
      this.$refs['form'].validate(async valid => {
        if (valid) {
          this.dataBtnLoading = true
          if (type === 'add') {
            res = await Data.add(this.apiUrl, this.formData)
            tip = '添加成功'
          }
          if (type === 'edit') {
            if (objData) {
              res = await Data.edit(this.apiUrl, objData)
            } else {
              res = await Data.edit(this.apiUrl, this.formData)
            }
            tip = '修改成功'
          }
          if (res) {
            Notification({
              message: message || tip
            })
            this.fetchList()
            this.dataBtnLoading = false
            this.dialogVisible = false
          }
        }
      })
    },
    async formCheck() {
      if (await this.$refs['form'].validate() === true) {
        return true
      } else {
        return false
      }
    },
    async formRequest({ type, formData = null, message = null }) {
      let res
      if (await this.formCheck()) {
        const obj = JSON.parse(JSON.stringify(this.formData))
        if (formData) {
          for (const key in formData) {
            formData[key] = obj[key]
          }
        }
        loding = Loading.service()
        if (type === 'add') {
          res = await Data.add(this.apiUrl, formData || obj)
          if (!message) {
            message = '添加成功'
            // console.log(this.formData)
          }
        }
        if (type === 'edit') {
          // console.log(456)
          res = await Data.edit(this.apiUrl, formData || obj)
          if (!message) {
            message = '修改成功'
            // this.$router.back()
          }
        }
        this.$nextTick(() => { // 以服务的方式调用的 Loading 需要异步关闭
          loding.close()
        })
        if (res) {
          Notification({
            message: message
          })
          this.fetchList()
          this.dialogVisible = false
        }
      }
    },
    timeChange(value) {
      if (value) {
        this.formData.startTime = value[0]
        this.formData.endTime = value[1]
      }
    },
  }
}
